package com.ruoyi.app.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.app.MaintainerEmployeesVillage;
import com.tdd.wx.users.api.WxUserServiceApi;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.app.service.IMaintainerEmployeesVillageService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 服务商-员工-小区关联Controller
 *
 * @author lobyliang
 * @date 2022-01-23
 */
@RestController
@RequestMapping("maintainerEmployeesVillage")
@Api(tags = "服务商员工小区")
public class MaintainerEmployeesVillageController extends BaseController
{
    @Autowired
    private IMaintainerEmployeesVillageService maintainerEmployeesVillageService;

    @DubboReference(version = "3.0.0" , interfaceClass = WxUserServiceApi.class, interfaceName = "WxUserService" , lazy = true, check = false)
    private WxUserServiceApi wxUserServiceApi;

    /**
     * 查询服务商-员工-小区关联列表
     */
    @RequiresPermissions("app:maintainerEmployeesVillage:list")
    @GetMapping("/list")
    public TableDataInfo list(MaintainerEmployeesVillage maintainerEmployeesVillage)
    {
        startPage();
        List<MaintainerEmployeesVillage> list = maintainerEmployeesVillageService.selectMaintainerEmployeesVillageList(maintainerEmployeesVillage);
        return getDataTable(list);
    }

    /**
     * 导出服务商-员工-小区关联列表
     */
    @RequiresPermissions("app:maintainerEmployeesVillage:export")
    @Log(title = "服务商-员工-小区关联", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MaintainerEmployeesVillage maintainerEmployeesVillage) throws IOException
    {
        List<MaintainerEmployeesVillage> list = maintainerEmployeesVillageService.selectMaintainerEmployeesVillageList(maintainerEmployeesVillage);
        ExcelUtil<MaintainerEmployeesVillage> util = new ExcelUtil<MaintainerEmployeesVillage>(MaintainerEmployeesVillage.class);
        util.exportExcel(response, list, "服务商-员工-小区关联数据");
    }

    /**
     * 获取服务商-员工-小区关联详细信息
     */
    @RequiresPermissions("app:maintainerEmployeesVillage:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(maintainerEmployeesVillageService.selectMaintainerEmployeesVillageById(id));
    }

    /**
     * 新增服务商-员工-小区关联
     */
    @RequiresPermissions("app:maintainerEmployeesVillage:add")
    @Log(title = "服务商-员工-小区关联", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MaintainerEmployeesVillage maintainerEmployeesVillage)
    {
        return toAjax(maintainerEmployeesVillageService.insertMaintainerEmployeesVillage(maintainerEmployeesVillage));
    }

    /**
     * 修改服务商-员工-小区关联
     */
    @RequiresPermissions("app:maintainerEmployeesVillage:edit")
    @Log(title = "服务商-员工-小区关联", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MaintainerEmployeesVillage maintainerEmployeesVillage)
    {
        return toAjax(maintainerEmployeesVillageService.updateMaintainerEmployeesVillage(maintainerEmployeesVillage));
    }

    /**
     * 删除服务商-员工-小区关联
     */
    @RequiresPermissions("app:maintainerEmployeesVillage:remove")
    @Log(title = "服务商-员工-小区关联", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(maintainerEmployeesVillageService.deleteMaintainerEmployeesVillageByIds(ids));
    }

    @ApiOperation("根据服务商用户id查询")
    @GetMapping("findByMaintainerUID")
    public R<List<MaintainerEmployeesVillage>> findByMaintainerUID(Long uid){
        return R.ok(maintainerEmployeesVillageService.findByMaintainerUID(uid));
    }

    @ApiOperation("根据员工unionid查询")
    @GetMapping("findByEmployeesUnionid")
    public R<List<MaintainerEmployeesVillage>> findByEmployeesUnionid(String unionid){
        return R.ok(maintainerEmployeesVillageService.findByEmployeesUnionid(unionid));
    }

    @GetMapping("findEUidAndMid")
    public R<List<MaintainerEmployeesVillage>> findEUidAndMid(String eUnionid,Long mUid){
        return R.ok(maintainerEmployeesVillageService.findEUidAndMid(eUnionid,mUid));
    }

    @ApiOperation("保存")
    @GetMapping("save")
    public R save(String employeesUnionid,Long maintainerUserId,String villageCodes){
        maintainerEmployeesVillageService.save(employeesUnionid,maintainerUserId, villageCodes);
        return R.ok();
    }

    @ApiOperation("员工列表")
    @GetMapping("employeesList")
    public R employeesList(Page<Map> page){
        Long maintainerId = SecurityUtils.getUserId();
        maintainerEmployeesVillageService.employeesList(page,maintainerId);
        for (Map m : page.getRecords()) {
            String eid = MapUtil.getStr(m,"employeesUnionid",null);
            if(StrUtil.isNotEmpty(eid)){
                m.put("employeesInfo",wxUserServiceApi.findByUnionId(eid));
            }
        }
        return R.ok(page);
    }

    @ApiOperation("取消绑定")
    @GetMapping("cancelBinding")
    public R cancelBinding(String employeesUnionid){
//        maintainerEmployeesVillageService.removeById(id);
        Long maintainerId = SecurityUtils.getUserId();
        maintainerEmployeesVillageService.remove(new LambdaQueryWrapper<MaintainerEmployeesVillage>().eq(MaintainerEmployeesVillage::getEmployeesUnionid,employeesUnionid).eq(MaintainerEmployeesVillage::getMaintainerUserId,maintainerId));
        return R.ok();
    }

    @ApiOperation("分配员工小区")
    @GetMapping("fpVillage")
    public R fpVillage(String employeesUnionid,String villageCodes){
        Long mid = SecurityUtils.getUserId();
        if(mid == null || StrUtil.isEmpty(villageCodes)){
            return R.fail();
        }
        List<String> vCodes1 = Arrays.asList(villageCodes.split(","));
        List<String> vCodes = new ArrayList<>(vCodes1);
        if(vCodes.size() <= 0){
            return R.fail();
        }
        List<MaintainerEmployeesVillage> oldVillageList = maintainerEmployeesVillageService.findByEmployeesUnionid(employeesUnionid);
        if(oldVillageList.size() > 0){
            List<Long> delList = oldVillageList.stream().filter(s->!vCodes.contains(s.getVillageCode())).map(MaintainerEmployeesVillage::getId).collect(Collectors.toList());
            List<String> oldVCodesList = oldVillageList.stream().map(MaintainerEmployeesVillage::getVillageCode).collect(Collectors.toList());
            if(delList.size() > 0){
                maintainerEmployeesVillageService.removeBatchByIds(delList);
            }
            vCodes.removeAll(oldVCodesList);
        }
        if(vCodes.size()>0){
            maintainerEmployeesVillageService.save(employeesUnionid,mid,StrUtil.join(",",vCodes));
        }
        return R.ok();
    }

    /**
     * 基于 员工id 查询 员工服务商关联信息
     * @author songping
     * @date 2022-04-07
     * @param empUnionId 员工的uid
     * @return
     */
    @GetMapping("findMaintainerIdByEmpUnionId")
    public R<MaintainerEmployeesVillage>  findMaintainerIdByEmpUnionId(@RequestParam("empUnionId") String empUnionId){
        MaintainerEmployeesVillage data =  maintainerEmployeesVillageService.findMaintainerIdByEmpUnionId(empUnionId);
        return R.ok(data);
    }
}
